import socket, sys, json

user_data = open('user_list.json')
user_list = json.load(user_data)
user_data.close()

#username=['root','admin','manager']
username = user_list['username']

#password=['root','pass','friend']
password = user_list['password']

arguments = sys.argv

#address = '127.0.0.1'
address = str(arguments[1])

#port = 10000
port = int(arguments[2])

report_file = str(arguments[3])

print 'brute_client test begin'
print 'address:' , address
print 'port:' , port
print 'report_file:' , report_file

data_length = 64

expected = ['login:','Password:','Last login:','Login incorrect','Connection closed by foreign host.']
expected_alt = ['username:','password:','success','login failed','Connection closed by foreign host.']

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (address,port)
login_report = ''
user_count = 0
pass_count = 0
return_code = 0

try:
    sock.connect(server_address)
    while True:
        data = sock.recv(data_length)
        if data:
            print data
            if data == expected[2]:
                #success statement
                login_report += 'Username:' + username[user_count-1] + '\n'
                login_report += 'Password:' + password[pass_count-1] + '\n'
                login_report += 'Login success!' + '\n'
                return_code = 1
                break
            elif data[-6:] == expected[0]:
                #username request
                sock.sendall(username[user_count])
                user_count += 1
                if len(username) < user_count:
                    login_report += 'Failed at username\n'
                    break
            elif data == expected[1]:
                #password request
                sock.sendall(password[pass_count])
                pass_count += 1
                if len(password) < pass_count:
                    login_report += 'Failed at password\n'
                    break
            elif data == expected[4]:
                #connection closed after 3 tries statement
                login_report += data + '\n'
                login_report += 'Failed after retries.\n'
                break
except Exception as e:
    login_report += 'Exception %s\n' % str(e)

with open(report_file, "w") as file:
    file.write(login_report)
sock.close()
sys.exit(return_code)
